import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
import Fontisto from 'react-native-vector-icons/Fontisto';
import {StylesConstant} from '../Constant';

export default class Checkbox extends React.Component {
    // props
    constructor(props) {
      super(props);
      this.state = {
        checked: props.checked ? props.checked : [],
      };
    }

    shouldComponentUpdate(nextProps, nextState) {
        // 旧数据
        const current = this.props.checked;
        // 新数据
        const next = nextProps.checked;
        const flag = JSON.stringify(current) !== JSON.stringify(next)
        if(flag){
          this.state.checked = next
        }
        return flag
    }

    render() {
      const dataArr = this.props.data || [];
      return (
        <View style={this.props.checkboxStyle}>
          {/* checkItem */}
          {dataArr.length > 0 ? (
            this.renderCheckItem(dataArr)
          ) : (
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <Text style={{color: '#ccc', fontSize: 16}}>暂无数据</Text>
            </View>
          )}
        </View>
      );
    }

  // 渲染checkItem
  renderCheckItem(dataArr) {
    const iconColor = StylesConstant.themeIconColor;
    const checkedArr = this.state.checked;
    return dataArr.map((item, index) => {
      return (
        <TouchableOpacity
          style={styles.item}
          activeOpacity={0.5}
          key={index}
          onPress={() => this.setData(item)}>
          <Fontisto
            style={styles.checkIcon}
            name={
              checkedArr.includes(item.value)
                ?  'radio-btn-active'
                :  'radio-btn-passive'
            }
            size={14}
            color={iconColor}
          />
          <Text style={styles.label}>{item.label}</Text>
        </TouchableOpacity>
      );
    });
  }
  // 单击某一项
  setData(item) {
    this.props.onChange(item);
  }

}

const styles = StyleSheet.create({
  item: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 20,
  },
  checkIcon: {
    paddingRight: 10,
  },
  label: {
    fontSize: 16,
  },
});
